package com.dw.etl.core.controller;

import com.dw.etl.common.base.BaseException;
import com.dw.etl.common.base.BaseResult;
import com.dw.etl.common.constant.CommonResultConstant;
import com.dw.etl.common.util.SpringBeanUtil;
import com.dw.etl.common.vo.PaginationVO;
import com.dw.etl.core.api.BaseIndexConfService;
import com.dw.etl.core.api.EtlBaseService;
import com.dw.etl.core.api.EtlRunService;
import com.dw.etl.core.bean.model.EtlBase;
import com.dw.etl.core.bean.vo.JobQryVO;
import com.dw.etl.core.utils.EtlUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * Created by liujunlei on 2021/5/21.
 */
@RestController
@RequestMapping("/etl/etlBase/")
@Api(tags="任务运行")
public class RunJobController {

    @Resource(name = "myJobLauncher")
    SimpleJobLauncher myJobLauncher;

    @Autowired
    EtlBaseService etlBaseService;

    @Autowired
    EtlRunService etlRunService;

    @ApiOperation(value="自动建表")
    @RequestMapping(value="autoCreateTable", method= RequestMethod.GET)
    public BaseResult autoCreateTable(Long idBase) throws BaseException {
        etlRunService.autoCreatTable(idBase);
        return new BaseResult(CommonResultConstant.SUCCESS, "执行成功");
    }

    @ApiOperation(value="运行基础抽取任务")
    @RequestMapping(value="runBaseJob", method= RequestMethod.GET)
    public BaseResult runSingleJob(JobQryVO jobQryVO) throws BaseException {
        String dBegin = jobQryVO.getdBegin();
        String dEnd = jobQryVO.getdEnd();
        if(StringUtils.isEmpty(dBegin) || StringUtils.isEmpty(dBegin)) {
            throw new BaseException("时间不能为空");
        }
        Date dtBegin = EtlUtil.getDate(dBegin,jobQryVO.getEuDtDim());
        Date dtEnd = EtlUtil.getDate(dEnd,jobQryVO.getEuDtDim());

        int counterStop = 0;//计算器，防止死循环，无实际意义

        EtlBase etlBaseModel = new EtlBase();
        etlBaseModel.setSdJbcls(jobQryVO.getSdJbcls());
        etlBaseModel.setIdBase(jobQryVO.getIdBase());
        List<EtlBase> etlBaseList = etlBaseService.findAllByModel(etlBaseModel);
        /**
         * todo by xxx 稍后处理
         * 校验是否自动创建表
         * 如果是校验写入表是否已创建，未创建的自动创建
         */
        Job job;
        try{
            JobParameters parameters;
            Date dtNext;
            JobExecution jobExecution;
            while(dtBegin.before(dtEnd) && counterStop<10000) {
                dtNext = EtlUtil.getNextDate(dtBegin,jobQryVO.getEuDtDim());
                for(EtlBase etlBase:etlBaseList) {
                    parameters =  new JobParametersBuilder()
                            .addDate("dtBegin",dtBegin)
                            .addDate("dtEnd",dtNext)
                            .addDate("dtNow",new Date())
                            .addString("tableName",etlBase.getTbTar())
                            .addLong("idBase",etlBase.getIdBase())
                            .addLong("idDbSou",etlBase.getIdDbSou())
                            .addLong("idDbTar",etlBase.getIdDbTar())
                            .addString("qSql",etlBase.getQsql()).toJobParameters();
                    job = (Job)SpringBeanUtil.getBean(etlBase.getIdJb());
                    jobExecution = myJobLauncher.run(job,parameters);
                }
                dtBegin = dtNext;
                counterStop++;
            }
        } catch (Exception e) {
            throw new BaseException("抽取任务异常",e);
        }
        return new BaseResult(CommonResultConstant.SUCCESS, "执行成功");
    }

    @Autowired
    private BaseIndexConfService baseIndexConfService;

    @ApiOperation(value="运行DM抽取任务")
    @RequestMapping(value="runDMJob", method= RequestMethod.GET)
    public BaseResult runDMJob(JobQryVO jobQryVO) throws BaseException {
        String dBegin = jobQryVO.getdBegin();
        String dEnd = jobQryVO.getdEnd();
        if(StringUtils.isEmpty(dBegin) || StringUtils.isEmpty(dBegin)) {
            throw new BaseException("时间不能为空");
        }
        Date dtBegin = EtlUtil.getDate(dBegin,jobQryVO.getEuDtDim());
        Date dtEnd = EtlUtil.getDate(dEnd,jobQryVO.getEuDtDim());
        List<String> sqlList = baseIndexConfService.findAllSql();
        Job job;
        int counterStop = 0;//计算器，防止死循环，无实际意义
        try{
            JobParameters parameters;
            Date dtNext;
            JobExecution jobExecution;
            while(dtBegin.before(dtEnd) && counterStop<10000) {
                dtNext = EtlUtil.getNextDate(dtBegin,jobQryVO.getEuDtDim());
                for(String sql:sqlList) {
                    parameters =  new JobParametersBuilder()
                            .addDate("dtBegin",dtBegin)
                            .addDate("dtEnd",dtNext)
                            .addDate("dtNow",new Date())
                            /*.addString("tableName",etlBase.getTbTar())
                            .addLong("idBase",etlBase.getIdBase())
                            .addLong("idDbSou",etlBase.getIdDbSou())
                            .addLong("idDbTar",etlBase.getIdDbTar())*/
                            .addString("qSql",sql).toJobParameters();
                    job = (Job)SpringBeanUtil.getBean("");
                    jobExecution = myJobLauncher.run(job,parameters);
                }
                dtBegin = dtNext;
                counterStop++;
            }
        } catch (Exception e) {
            throw new BaseException("抽取任务异常",e);
        }
        return new BaseResult(CommonResultConstant.SUCCESS, null);
    }
}
